<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="合同编号" prop="contractNo">
        <el-input v-model="queryParams.contractNo" placeholder="请输入合同编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="签约日期">
        <el-date-picker v-model="daterangeSignDate" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="付款周期" prop="paymentCycle">
        <el-select v-model="queryParams.paymentCycle" placeholder="请选择付款周期" clearable>
          <el-option v-for="dict in dict.type.zk_payment_cycle" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="合同状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择合同状态" clearable>
          <el-option v-for="dict in dict.type.zk_contract_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['rent:contract:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['rent:contract:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['rent:contract:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['rent:contract:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属房东" align="center" prop="landlordName" />
      <el-table-column label="租客" align="center" prop="tenantName" />
      <el-table-column label="房源" align="center" prop="propertyName" />
      <el-table-column label="合同编号" align="center" prop="contractNo" />
      <el-table-column label="月租金" align="center" prop="rentAmount" />
      <el-table-column label="押金金额" align="center" prop="depositAmount" />
      <el-table-column label="付款周期" align="center" prop="paymentCycle">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.zk_payment_cycle" :value="scope.row.paymentCycle" />
        </template>
      </el-table-column>
      <el-table-column label="下次付款日期" align="center" prop="nextPaymentDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.nextPaymentDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.zk_contract_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['rent:contract:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['rent:contract:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改租赁合同对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="租客" prop="tenantId">
              <el-select v-model="form.tenantId" placeholder="请选择租客">
                <el-option v-for="tenant in listTenant" :key="tenant.id" :label="tenant.name"
                  :value="tenant.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房源" prop="propertyId">
              <el-select v-model="form.propertyId" placeholder="请选择房源">
                <el-option v-for="property in listProperty" :key="property.id" :label="property.propertyName"
                  :value="property.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractNo">
              <el-input v-model="form.contractNo" placeholder="请输入合同编号" class="input" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签约日期" prop="signDate">
              <el-date-picker clearable v-model="form.signDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择签约日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="起租日期" prop="startDate">
              <el-date-picker clearable v-model="form.startDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择起租日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到期日期" prop="endDate">
              <el-date-picker clearable v-model="form.endDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择到期日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="月租金" prop="rentAmount">
              <el-input v-model="form.rentAmount" placeholder="请输入月租金" class="input"  />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="押金金额" prop="depositAmount">
              <el-input v-model="form.depositAmount" placeholder="请输入押金金额" class="input"  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="付款周期" prop="paymentCycle">
              <el-select v-model="form.paymentCycle" placeholder="请选择付款周期">
                <el-option v-for="dict in dict.type.zk_payment_cycle" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次付款日期" prop="nextPaymentDate">
              <el-date-picker clearable v-model="form.nextPaymentDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择下次付款日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="合同状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.zk_contract_status" :key="dict.value"
              :label="dict.value">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="合同备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listAllProperty,
  } from "@/api/rent/property"

  import {
    listAllTenant,
  } from "@/api/rent/tenant"

  import {
    listContract,
    getContract,
    delContract,
    addContract,
    updateContract
  } from "@/api/rent/contract"

  export default {
    name: "Contract",
    dicts: ['zk_contract_status', 'zk_payment_cycle'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 租赁合同表格数据
        contractList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 合同备注时间范围
        daterangeStartDate: [],
        // 合同备注时间范围
        daterangeEndDate: [],
        // 合同备注时间范围
        daterangeSignDate: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          landlordId: null,
          tenantId: null,
          propertyId: null,
          contractNo: null,
          startDate: null,
          endDate: null,
          signDate: null,
          rentAmount: null,
          depositAmount: null,
          paymentCycle: null,
          nextPaymentDate: null,
          status: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          landlordId: [{
            required: true,
            message: "所属房东ID不能为空",
            trigger: "blur"
          }],
          tenantId: [{
            required: true,
            message: "租客ID不能为空",
            trigger: "blur"
          }],
          propertyId: [{
            required: true,
            message: "房源ID不能为空",
            trigger: "blur"
          }],
          contractNo: [{
            required: true,
            message: "合同编号不能为空",
            trigger: "blur"
          }],
          startDate: [{
            required: true,
            message: "起租日期不能为空",
            trigger: "blur"
          }],
          endDate: [{
            required: true,
            message: "到期日期不能为空",
            trigger: "blur"
          }],
          signDate: [{
            required: true,
            message: "签约日期不能为空",
            trigger: "blur"
          }],
          rentAmount: [{
            required: true,
            message: "月租金不能为空",
            trigger: "blur"
          }],
          depositAmount: [{
            required: true,
            message: "押金金额不能为空",
            trigger: "blur"
          }],
          paymentCycle: [{
            required: true,
            message: "付款周期不能为空",
            trigger: "change"
          }],
          nextPaymentDate: [{
            required: true,
            message: "下次付款日期不能为空",
            trigger: "blur"
          }],
        },
        listProperty: [], //房源信息
        listTenant: [], //租客信息
      }
    },
    created() {
      this.init();
    },
    methods: {
      //初始化数据
      init() {
        //加载房源列表
        listAllProperty({}).then(response => {
          this.listProperty = response.rows
        })
        //加载租客列表
        listAllTenant({}).then(response => {
          this.listTenant = response.rows
        })
        //加载合同列表
        this.getList()
      },
      /** 查询租赁合同列表 */
      getList() {
        this.loading = true
        this.queryParams.params = {}
        if (null != this.daterangeStartDate && '' != this.daterangeStartDate) {
          this.queryParams.params["beginStartDate"] = this.daterangeStartDate[0]
          this.queryParams.params["endStartDate"] = this.daterangeStartDate[1]
        }
        if (null != this.daterangeEndDate && '' != this.daterangeEndDate) {
          this.queryParams.params["beginEndDate"] = this.daterangeEndDate[0]
          this.queryParams.params["endEndDate"] = this.daterangeEndDate[1]
        }
        if (null != this.daterangeSignDate && '' != this.daterangeSignDate) {
          this.queryParams.params["beginSignDate"] = this.daterangeSignDate[0]
          this.queryParams.params["endSignDate"] = this.daterangeSignDate[1]
        }
        listContract(this.queryParams).then(response => {
          this.contractList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          landlordId: null,
          tenantId: null,
          propertyId: null,
          contractNo: null,
          startDate: null,
          endDate: null,
          signDate: null,
          rentAmount: null,
          depositAmount: null,
          paymentCycle: null,
          nextPaymentDate: null,
          status: null,
          remark: null,
          createTime: null,
          updateTime: null
        }
        this.resetForm("form")
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.daterangeStartDate = []
        this.daterangeEndDate = []
        this.daterangeSignDate = []
        this.resetForm("queryForm")
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = "添加租赁合同"
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const id = row.id || this.ids
        getContract(id).then(response => {
          this.form = response.data
          this.open = true
          this.title = "修改租赁合同"
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateContract(this.form).then(response => {
                this.$modal.msgSuccess("修改成功")
                this.open = false
                this.getList()
              })
            } else {
              addContract(this.form).then(response => {
                this.$modal.msgSuccess("新增成功")
                this.open = false
                this.getList()
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids
        this.$modal.confirm('是否确认删除租赁合同编号为"' + ids + '"的数据项？').then(function() {
          return delContract(ids)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        }).catch(() => {})
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('rent/contract/export', {
          ...this.queryParams
        }, `contract_${new Date().getTime()}.xlsx`)
      }
    }
  }
</script>
<style >
  .input{width: 220px;}

</style>
